package com.lzh.edu.controller;

import com.lzh.commonutils.CommonResult;
import com.lzh.commonutils.JwtUtils;
import com.lzh.edu.entity.AdUser;
import com.lzh.edu.service.AdUserService;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

/**
 * @author lzhstart
 * @create 2021/4/22 9:27
 */
@RestController
@CrossOrigin
@RequestMapping("/edu/user")
public class AdUserController {

    @Autowired
    private AdUserService adUserService;

    /**
     * 管理原用户注册
     * @param adUser
     * @return
     */
    @ApiOperation(value = "用户注册")
    @PostMapping("/register")
    public CommonResult register(@RequestBody AdUser adUser) {
        boolean save = adUserService.saveUser(adUser);
        if (save) {
        return CommonResult.ok().message("用户注册成功！");
        }else return CommonResult.error().message("用户注册失败");
    }

    /**
     * 管理员登录
     * @return
     */
    @ApiOperation(value = "用户登录")
    @PostMapping("/login")
    public CommonResult login(@RequestBody AdUser adUser) {
        if (StringUtils.isEmpty(adUser) || StringUtils.isEmpty(adUser.getUsername()) || StringUtils.isEmpty(adUser.getPassword())) {
            return CommonResult.error().message("用户名或密码有误！");
        }
        String token = adUserService.login(adUser);
        if (token != null) {
        return CommonResult.ok().data("token",token);
        }else {
            return CommonResult.error().message("登录失败");
        }
    }

    @ApiOperation(value = "查询登录用户信息")
    @GetMapping("/info")
    public CommonResult info(@RequestParam(value = "token") String token) {
        String userId = JwtUtils.getadminIdByToken(token);
        AdUser adUser = adUserService.getInfo(userId);
        return CommonResult.ok().data("roles","admin").data("name",adUser.getUsername()).data("avatar",adUser.getImage());
    }

    @ApiOperation(value = "注销用户")
    @PostMapping("/logout")
    public CommonResult logout() {
        return CommonResult.ok();
    }
}
